<template>
  <!-- 频道文章列表组件 -->
  <div class="article-list">
    <van-pull-refresh success-duration="1000" :success-text="isSuccessText" v-model="isRefreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多内容了..."
        :error.sync="error"
        error-text="请求失败，点击重新加载..."
        @load="onLoad"
      >
        <!-- 列表项展示组件 -->
        <article-item v-for="(article, i) in actircleListData" :key="i" :article="article"></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
// 导入频道文章列表展示项
import ArticleItem from '@/components/acticle-item/index'
// 导入请求接口
import { getRecommendNews } from '@/api/article'
export default {
  name: 'ArticleList',
  components: {
    'article-item': ArticleItem
  },
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      // 文章列表数据
      actircleListData: [],
      // List 错误提示，true即可显示错误提示，点击触发onload事件
      error: false,
      // List的加载状态
      loading: false,
      // List数据加载完毕状态
      finished: false,
      timestamp: null,
      // Pull-refresh 下拉刷新成功提示文案
      isSuccessText: '',
      // Pull-refresh下拉刷新加载状态
      isRefreshing: false
    }
  },
  methods: {
    // List内置加载事件，滚动条与底部距离小于 offset 时触发默认300
    async onLoad () {
      try {
        const { data: res } = await getRecommendNews({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        const { results } = res.data
        // 将列表项数据对象添加到空数组中
        this.actircleListData.push(...results)
        // 关闭Vant组件List的加载状态图标
        this.loading = false
        // 判断数据是否加载结束
        if (results.length) {
          this.timestamp = res.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        this.loading = false
        this.error = true
      }
    },
    // 触发下拉刷新调用函数
    async onRefresh () {
      try {
        const { data } = await getRecommendNews({
          channel_id: this.channels.id,
          timestamp: Date.now(),
          with_top: 1
        })
        const { results } = data.data
        this.actircleListData.unshift(...results)
        this.isRefreshing = false
        this.isSuccessText = `刷新成功，更新了${results.length}条信息`
        this.$toast.success('刷新成功...')
      } catch (err) {
        console.dir(err)
        // 数据刷新错误也需要将下拉刷新的状态进行关闭
        this.isRefreshing = false
        this.$toast.fail('刷新出错啦...')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.article-list {
 height: 78vh;
 overflow-y: auto;
}
</style>
